package com.simon.jkxj.ui.diet;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.simon.jkxj.R;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.formatter.ValueFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class BloodPressureRecordActivity extends AppCompatActivity {
    public static class BloodPressureRecord {
        public int sbp; // 收缩压
        public int dbp; // 舒张压
        public int hr;  // 心率
        public long time;
        public BloodPressureRecord(int sbp, int dbp, int hr, long time) {
            this.sbp = sbp;
            this.dbp = dbp;
            this.hr = hr;
            this.time = time;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blood_pressure_record);
        ImageView btnAdd = findViewById(R.id.btn_add);
        ImageView btnBack = findViewById(R.id.btn_back);
        if (btnBack != null) {
            btnBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BloodPressureRecordActivity.this, BloodPressureAddActivity.class);
                startActivityForResult(intent, 1002);
            }
        });
        updateChartAndStats();
        TextView tvDate = findViewById(R.id.tv_date);
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM月dd日", Locale.getDefault());
        String dateStr = dateFormat.format(new Date());
        tvDate.setText(dateStr);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1002 && resultCode == RESULT_OK) {
            int sbp = data.getIntExtra("sbp", 0);
            int dbp = data.getIntExtra("dbp", 0);
            int hr = data.getIntExtra("hr", 0);
            long time = data.getLongExtra("bp_time", System.currentTimeMillis());
            BloodPressureDataManager.addRecord(new BloodPressureRecord(sbp, dbp, hr, time));
            updateChartAndStats();
        }
    }

    private void updateChartAndStats() {
        List<BloodPressureRecord> recordList = BloodPressureDataManager.getRecords();
        // 1. 以最新日期为中心，筛选前后共7天的数据
        if (recordList.size() == 0) {
            LineChart chart = findViewById(R.id.line_chart);
            chart.clear();
            // ... existing code ...
            return;
        }
        // 找到最新一条记录的日期（天）
        BloodPressureRecord latest = recordList.get(recordList.size()-1);
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(latest.time);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        long centerDay = cal.getTimeInMillis();
        // 计算前后3天的时间戳
        long startDay = centerDay - 3 * 24 * 60 * 60 * 1000L;
        long endDay = centerDay + 3 * 24 * 60 * 60 * 1000L;
        // 统计用
        int high = 0, low = 0, normal = 0;
        int sumSbp = 0, sumDbp = 0, sumHr = 0, count = 0;
        // 曲线图数据
        List<Entry> sbpEntries = new ArrayList<>();
        List<Entry> dbpEntries = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd", Locale.getDefault());
        // 以天为横坐标，x=0为startDay，x=6为endDay
        for (int i = 0; i < recordList.size(); i++) {
            BloodPressureRecord r = recordList.get(i);
            // 只统计7天内的数据
            Calendar c = Calendar.getInstance();
            c.setTimeInMillis(r.time);
            c.set(Calendar.HOUR_OF_DAY, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MILLISECOND, 0);
            long day = c.getTimeInMillis();
            if (day < startDay || day > endDay) continue;
            int dayIndex = (int)((day - startDay) / (24 * 60 * 60 * 1000L)); // 0~6
            sbpEntries.add(new Entry(dayIndex, r.sbp));
            dbpEntries.add(new Entry(dayIndex, r.dbp));
            sumSbp += r.sbp;
            sumDbp += r.dbp;
            sumHr += r.hr;
            count++;
            if (r.sbp >= 140 || r.dbp >= 90) high++;
            else if (r.sbp < 90 || r.dbp < 60) low++;
            else normal++;
        }
        LineChart chart = findViewById(R.id.line_chart);
        if (sbpEntries.size() > 0) {
            LineDataSet sbpDataSet = new LineDataSet(sbpEntries, "收缩压");
            sbpDataSet.setCircleRadius(4f);
            sbpDataSet.setLineWidth(2f);
            sbpDataSet.setColor(0xFF2196F3);
            sbpDataSet.setCircleColor(0xFF2196F3);
            sbpDataSet.setValueTextSize(10f);
            LineDataSet dbpDataSet = new LineDataSet(dbpEntries, "舒张压");
            dbpDataSet.setCircleRadius(4f);
            dbpDataSet.setLineWidth(2f);
            dbpDataSet.setColor(0xFF4CAF50);
            dbpDataSet.setCircleColor(0xFF4CAF50);
            dbpDataSet.setValueTextSize(10f);
            LineData lineData = new LineData(sbpDataSet, dbpDataSet);
            chart.setData(lineData);
        } else {
            chart.clear();
        }
        // 设置x轴为日期，显示7天
        XAxis xAxis = chart.getXAxis();
        xAxis.setAxisMinimum(0f);
        xAxis.setAxisMaximum(6f);
        xAxis.setLabelCount(7, true);
        xAxis.setGranularity(1f);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        // 生成7天的日期标签
        final String[] dateLabels = new String[7];
        for (int i = 0; i < 7; i++) {
            Calendar d = Calendar.getInstance();
            d.setTimeInMillis(startDay + i * 24 * 60 * 60 * 1000L);
            dateLabels[i] = sdf.format(d.getTime());
        }
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                int idx = Math.round(value);
                if (idx < 0 || idx > 6) return "";
                return dateLabels[idx];
            }
        });
        chart.getAxisLeft().setAxisMinimum(40f);
        chart.getAxisLeft().setAxisMaximum(200f);
        chart.getAxisLeft().setLabelCount(5, true);
        chart.getAxisRight().setEnabled(false);
        chart.invalidate();

        // 2. 更新统计项
        ((TextView)findViewById(R.id.tv_high_count)).setText(high + " 次");
        ((TextView)findViewById(R.id.tv_low_count)).setText(low + " 次");
        ((TextView)findViewById(R.id.tv_normal_count)).setText(normal + " 次");
        // 3. 平均值
        TextView tvAvg = findViewById(R.id.tv_avg);
        if (count == 0) {
            tvAvg.setText("0/0 mmHg");
        } else {
            int avgSbp = sumSbp / count;
            int avgDbp = sumDbp / count;
            tvAvg.setText(String.format("%d/%d mmHg", avgSbp, avgDbp));
        }
        // 4. 最新血压值
        TextView tvSbp = findViewById(R.id.tv_sbp_value);
        TextView tvDbp = findViewById(R.id.tv_dbp_value);
        TextView tvHr = findViewById(R.id.tv_heart_rate_value);
        TextView tvStatus = findViewById(R.id.tv_blood_pressure_status);
        TextView tvAdvice = findViewById(R.id.tv_diet_advice);
        View cardAdvice = findViewById(R.id.card_diet_advice);
        if (recordList.size() == 0) {
            tvSbp.setText("0");
            tvDbp.setText("0");
            tvHr.setText("0");
            tvStatus.setText("");
            cardAdvice.setVisibility(View.GONE);
        } else {
            BloodPressureRecord latest2 = recordList.get(recordList.size()-1);
            tvSbp.setText(String.valueOf(latest2.sbp));
            tvDbp.setText(String.valueOf(latest2.dbp));
            tvHr.setText(String.valueOf(latest2.hr));
            if (latest2.sbp >= 140 || latest2.dbp >= 90) {
                tvStatus.setText("偏高");
                tvStatus.setTextColor(0xFFE91E63);
                cardAdvice.setVisibility(View.VISIBLE);
                tvAdvice.setText("饮食建议：\n1. 限制食盐摄入，每日不超过5克，避免腌制食品。\n2. 多吃新鲜蔬菜水果，补充钾、钙、镁等微量元素。\n3. 选择低脂奶制品、瘦肉、鱼类，减少动物脂肪摄入。\n4. 避免油腻、油炸、高热量食物，戒烟限酒。\n5. 保持规律作息，适量运动，减轻心理压力。");
            } else if (latest2.sbp < 90 || latest2.dbp < 60) {
                tvStatus.setText("偏低");
                tvStatus.setTextColor(0xFF03A9F4);
                cardAdvice.setVisibility(View.VISIBLE);
                tvAdvice.setText("饮食建议：\n1. 适当增加食盐摄入，保证充足饮水。\n2. 多吃富含蛋白质和维生素的食物，如瘦肉、蛋类、豆制品。\n3. 少量多餐，避免暴饮暴食和空腹。\n4. 早晨起床动作缓慢，防止体位性低血压。\n5. 必要时可饮用淡盐水或含糖饮料。");
            } else {
                tvStatus.setText("正常");
                tvStatus.setTextColor(0xFF4CAF50);
                cardAdvice.setVisibility(View.VISIBLE);
                tvAdvice.setText("饮食建议：\n1. 保持低盐、低脂、均衡饮食，预防血压波动。\n2. 多吃蔬菜水果，适量摄入优质蛋白。\n3. 规律作息，适度锻炼，保持良好心态。\n4. 定期监测血压，关注身体健康。");
            }
        }
    }
} 